import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import Qs from 'qs'
import defaultSettings from '@/settings'

// create an axios instance
const service = axios.create({
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 60000 // request timeout
})

const { vueElectron } = defaultSettings

// request interceptor
service.interceptors.request.use(
  config => {
    config.baseURL = store.state.app.server_api
    // 重新组装参数
    if (config.data && !(config.data instanceof FormData)) {
      config.data = Qs.stringify(config.data)
    }
    if (!config.headers.pbuss) {
      config.headers.pbuss = getToken()
    }
    if (vueElectron) {
      config.headers.custom_device = 'electron'
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    // 非固定格式返回数据，直接返回
    if (res.code === undefined || res.code === null) {
      return res
    }
    if (res.code !== 200) {
      // 账号登录问题
      if (res.msg.indexOf('登录') !== -1) {
        store.dispatch('user/resetToken').then(() => {
          window.reload()
        })
      } else {
        // 其它问题
        Message({
          message: res.msg || '出错了',
          type: 'error',
          duration: 5 * 1000
        })
      }

      return Promise.reject(new Error(res.msg || '出错了'))
    } else {
      return res
    }
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

service.all = function(promise) {
  return axios.all(promise)
}

service.spread = function(promise) {
  return axios.spread(promise)
}

export default service
